function waitForTurndown() {
  return new Promise((resolve) => {
    if (window.TurndownService) {
      resolve(window.TurndownService);
    } else {
      const checkInterval = setInterval(() => {
        if (window.TurndownService) {
          clearInterval(checkInterval);
          resolve(window.TurndownService);
        }
      }, 100);
    }
  });
}

function getSelectedHTML() {
  const selection = window.getSelection();
  if (!selection.rangeCount) return '';

  // 获取选中的范围
  const range = selection.getRangeAt(0);
  
  // 获取选中范围的完整HTML，包括父元素的样式
  const clonedSelection = range.cloneContents();
  const tempDiv = document.createElement('div');
  tempDiv.appendChild(clonedSelection);

  // 如果选中的内容在某个特定元素内（如标题、段落等），保留其标签
  const parentElement = range.commonAncestorContainer;
  if (parentElement.nodeType === Node.ELEMENT_NODE) {
    const tagName = parentElement.tagName.toLowerCase();
    if (['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'pre', 'code'].includes(tagName)) {
      const wrapper = document.createElement(tagName);
      wrapper.innerHTML = tempDiv.innerHTML;
      tempDiv.innerHTML = wrapper.outerHTML;
    }
  }

  return tempDiv.innerHTML;
}

async function convertToMarkdown(html) {
  if (!html) return '';
  
  console.log('Converting HTML:', html);
  
  try {
    const TurndownService = await waitForTurndown();
    const turndownService = new TurndownService({
      headingStyle: 'atx',
      codeBlockStyle: 'fenced',
      emDelimiter: '*',
      bulletListMarker: '-',
      strongDelimiter: '**',
      hr: '---',
      linkStyle: 'inlined'
    });

    // 添加自定义规则
    turndownService.addRule('headers', {
      filter: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
      replacement: function (content, node) {
        const level = node.tagName.charAt(1);
        return '\n' + '#'.repeat(level) + ' ' + content + '\n\n';
      }
    });

    // 代码块规则
    turndownService.addRule('codeBlock', {
      filter: function (node) {
        return (
          node.nodeName === 'PRE' ||
          (node.nodeName === 'CODE' && node.parentNode.nodeName === 'PRE')
        );
      },
      replacement: function (content) {
        return '\n```\n' + content.trim() + '\n```\n';
      }
    });

    // 内联代码规则
    turndownService.addRule('inlineCode', {
      filter: function (node) {
        return node.nodeName === 'CODE' && node.parentNode.nodeName !== 'PRE';
      },
      replacement: function (content) {
        return '`' + content.trim() + '`';
      }
    });

    // 表格规则
    turndownService.addRule('table', {
      filter: 'table',
      replacement: function (content, node) {
        const rows = node.rows;
        let markdown = '\n';

        // 处理表头
        if (rows.length > 0) {
          const headerCells = Array.from(rows[0].cells);
          markdown += '| ' + headerCells.map(cell => cell.textContent.trim()).join(' | ') + ' |\n';
          markdown += '| ' + headerCells.map(() => '---').join(' | ') + ' |\n';
        }

        // 处理表格内容
        for (let i = 1; i < rows.length; i++) {
          const cells = Array.from(rows[i].cells);
          markdown += '| ' + cells.map(cell => cell.textContent.trim()).join(' | ') + ' |\n';
        }

        return markdown + '\n';
      }
    });

    const markdown = turndownService.turndown(html);
    console.log('Converted Markdown:', markdown);
    return markdown;
  } catch (err) {
    console.error('Turndown 初始化失败:', err);
    return '';
  }
}

function copyToClipboard(text) {
  if (!text) {
    showNotification('没有可转换的内容');
    return;
  }

  return navigator.clipboard.writeText(text)
    .then(() => {
      showNotification('已复制到剪贴板');
      console.log('Copied to clipboard:', text); // 调试日志
    })
    .catch(err => {
      console.error('复制失败:', err);
      showNotification('复制失败，请重试');
    });
}

function showNotification(message) {
  const notification = document.createElement('div');
  notification.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    padding: 10px 20px;
    background-color: #333;
    color: white;
    border-radius: 4px;
    z-index: 10000;
    font-size: 14px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
  `;
  notification.textContent = message;
  document.body.appendChild(notification);
  
  setTimeout(() => {
    notification.style.opacity = '0';
    notification.style.transition = 'opacity 0.5s ease';
    setTimeout(() => notification.remove(), 500);
  }, 2000);
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === "convertToMarkdown") {
    console.log('接收到的原始内容:', request.text);
    
    // 获取选中内容的HTML
    const html = getSelectedHTML();
    console.log('获取到的HTML:', html);
    
    if (!html) {
      showNotification('请先选择要转换的内容');
      return;
    }
    
    // 使用HTML进行转换
    convertToMarkdown(html)
      .then(markdown => {
        if (markdown) {
          copyToClipboard(markdown);
        } else {
          showNotification('转换失败，请重试');
        }
      })
      .catch(err => {
        console.error('转换失败:', err);
        showNotification('转换失败，请重试');
      });
  }
}); 